const {
  app,
  BrowserWindow,
  ipcMain,
  shell,
  dialog,
  Tray,
  Menu,
  desktopCapturer,
} = require("electron");
const path = require("path");
const execa = require("execa");
const Store = require("electron-store");
const screenShot = require("screenshot-desktop");
let mainWindow = null;
const option = {
  name: "config", //文件名称,默认 config
  fileExtension: "json", //文件后缀,默认json
  encryptionKey: "aes-256-cbc", //对配置文件进行加密
  // clearInvalidConfig: true, // 发生 SyntaxError  则清空配置,
  cwd: "cache",
};
const ElectronStore = new Store(option);
let mainServer = null;
let tray = null;
let isDev = process.argv.indexOf("packenv") > 0;
/**
 * 创建进程监听逻辑
 */
const addProcess = () => {
  ipcMain.on("close", function (e) {
    console.log(e.sender.id);
    const win = BrowserWindow.fromId(e.sender.id);
    win && win.close();
  });
  ipcMain.on("open-url", function (e, url) {
    console.log(`About to open with default browser：${url}`);
    shell.openExternal(url);
  });
  ipcMain.on("get-path", function (e, type, cb) {
    dialog
      .showOpenDialog({ title: "选择路径", properties: [type] })
      .then(function (res) {
        e.reply("recive-path", res);
      });
  });
  ipcMain.on("full-screen", function (e, state) {
    mainWindow.setFullScreen(state);
  });
  ipcMain.on("mini-app", function (e) {
    // mainWindow.minimize()
    mainWindow.hide();
  });
  ipcMain.on("electron-store-set", (e, key, val) => {
    ElectronStore.set(key, val);
    e.returnValue = ElectronStore.get(key);
  });
  ipcMain.on("electron-store-get", (e, key) => {
    e.returnValue = ElectronStore.get(key);
  });
  ipcMain.on("electron-store-remove", (e, key) => {
    ElectronStore.delete(key);
    e.returnValue = ElectronStore.get(key);
  });
  ipcMain.on("electron-store-clear", (e) => {
    ElectronStore.clear();
    e.returnValue = "";
  });
  ipcMain.on("git-pull", (e, item) => {
    let file = path.resolve(__dirname, "./sh/pull.sh");
    let argStr = "";
    if (item instanceof Array) {
      let tempArr = [];
      item.forEach((val) => {
        val.path && val.desc && tempArr.push(val.path, val.desc);
      });
      argStr = tempArr.join(" ");
    } else if (item instanceof Object) {
      argStr = item.path && item.desc ? `${item.path} ${item.desc}` : "";
    }
    execa(`call ${file} ${argStr}`);
  });
};
/**
 * 创建托盘图标交互
 */
const createTray = () => {
  tray = new Tray("./electron.ico");
  let menuTip = Menu.buildFromTemplate([
    {
      click() {
        console.log("截屏");
        screenShot({ filename: "/screen_shot/test.jpg" })
          .then((imgPath) => {
            console.log(imgPath);
          })
          .catch((e) => {
            console.log(e);
          });
      },
      label: "截屏",
    },
    {
      click() {
        mainWindow.webContents.openDevTools({ mode: "detach" });
      },
      label: "打开调试",
    },
    {
      click() {
        mainWindow.show();
      },
      label: "打开程序",
    },
    {
      click() {
        mainWindow.close();
      },
      label: "退出程序",
    },
  ]);
  tray.setToolTip("electron测试程序");
  tray.on("click", () => {
    mainWindow.show();
  });
  tray.setContextMenu(menuTip);
};
/**
 * 创建应用窗口
 */
function createWindow() {
  mainWindow = new BrowserWindow({
    // maxWidth: 1280,
    minWidth: 1280,
    // maxHeight: 720,
    minHeight: 720,
    width: 1280,
    height: 720,
    frame: false,
    transparent: true,
    show: false,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
    },
  });

  mainWindow.once("ready-to-show", () => {
    console.log("ready-to-show");
    mainWindow.show();
  });
  if (isDev) {
    // let src = path.join(__dirname, "views/index.html");
    // console.log(src);
    // mainWindow.loadURL(src);
    // mainWindow.loadURL('http://localhost:3000')
    mainWindow.loadURL("http://localhost:8080/login");
    // mainWindow.loadURL('https://www.wasu.cn/')
    // mainWindow.webContents.openDevTools({ mode: 'detach' })
    // mainView.webContents.loadURL('http://localhost:8080')
    // otherView.webContents.loadURL('https://www.baidu.com')
  } else {
    const createServer = require("./server");
    mainServer = createServer(() => {
      mainWindow.loadURL("http://localhost:3000/login");
    });
  }
}

app.whenReady().then(() => {
  createWindow();
  addProcess();
  createTray();
});
/**
 * window环境关闭所有窗口退出程序
 */
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    mainServer && mainServer.close();
    app.quit();
  }
});
